package com.game.tank.bean;

import com.game.tank.TankFrame;
import com.game.tank.enums.Dir;
import com.game.tank.enums.TankGroup;
import com.game.tank.loader.ResourceMgr;

import java.awt.*;
import java.awt.image.BufferedImage;

public class Bullet {

    private static final int SPEED = 10;
    private int x,y;
    private Dir dir = Dir.UP;
    private TankGroup group = TankGroup.GOOD;
    public static int WIDTH = ResourceMgr.bulletU.getWidth();
    public static int HEIGHT = ResourceMgr.bulletU.getHeight();

    private boolean live = true;

    private Rectangle rect = new Rectangle();


    public boolean isLive() {
        return live;
    }

    private TankFrame tankFrame;

    public Bullet(int x, int y, Dir dir,TankGroup group,TankFrame tankFrame) {
        this.x = x;
        this.y = y;
        this.dir = dir;
        this.group = group;
        this.tankFrame = tankFrame;

        rect.x = x;
        rect.y = y;
        rect.width = WIDTH;
        rect.height = HEIGHT;
    }

    public void paint(Graphics graphics) {
        if (!isLive()) {
            tankFrame.bullets.remove(this);
        }

        Color c = graphics.getColor();
        BufferedImage bullet = null;
        switch (dir) {
            case LEFT:
                bullet = ResourceMgr.bulletL;
                break;
            case RIGHT:
                bullet = ResourceMgr.bulletR;
                break;
            case UP:
                bullet = ResourceMgr.bulletU;
                break;
            case DOWN:
                bullet = ResourceMgr.bulletD;
                break;
            default:
                bullet = ResourceMgr.bulletU;
                break;
        }
        graphics.drawImage(bullet, x, y, null);

        move();
    }

    public void die() {
        live = false;
    }
    private void move() {
        switch (dir) {
            case LEFT:
                x -= SPEED;
                break;
            case RIGHT:
                x += SPEED;
                break;
            case UP:
                y -= SPEED;
                break;
            case DOWN:
                y += SPEED;
                break;
        }
        if (x < 0 || y < 0 || x > TankFrame.GAME_WIDTH || y > TankFrame.GAME_HEIGHT) die();
        rect.x = x;
        rect.y = y;
    }

    public void collectWidth(Tank tank) {

        if (this.group == tank.getGroup()) return;
        if (rect.intersects(tank.getRect())) {
            tank.die();
            this.die();
            int bx = tank.getX() + Tank.WIDTH / 2 - Explode.WIDTH / 2;
            int by = tank.getY() + Tank.HEIGHT / 2 - Explode.HEIGHT / 2;
            tankFrame.explodes.add(new Explode(bx,by, tankFrame));
        }
    }
}
